<template>
  <div class="home-wrapper">
    <div class="search-bar">
      <button @click="showSearchBar()" class="search-btn">使用关键字搜索 问答/名师/作品/新闻</button>
    </div>
    <div class="banner-wrapper">
      <van-swipe :autoplay="3000">
        <van-swipe-item v-for="(banner, index) in banners" :key="index">
          <img @click="viewBanner(index)" v-lazy="banner.file" />
        </van-swipe-item>
      </van-swipe>
    </div>
    <div class="feature-wrapper">
      <router-link to="/master/list" class="feature-item">
        <img class="feature-img" src="../../assets/icon/icon_master.png" alt="" />
        <span>找名师</span>
      </router-link>
      <router-link to="/task/list" class="feature-item">
        <img class="feature-img" src="../../assets/icon/icon_task.png" alt="" />
        <span>任务大厅</span>
      </router-link>
      <router-link to="/painting/list" class="feature-item">
        <img class="feature-img" src="../../assets/icon/icon_gallery.png" alt="" />
        <span>展馆</span>
      </router-link>
      <router-link to="/news" class="feature-item">
        <img class="feature-img" src="../../assets/icon/icon_news.png" alt="" />
        <span>资讯</span>
      </router-link>
    </div>
    <div class="task-wrapper">
      <ul class="tags-tab">
        <li v-for="(item, index) in questionData.catalogs" @click="switchActive(0,index)" :class="['tag-item', questionData.active == index ? 'tag-selected' : '']">{{ item.name }}</li>
      </ul>
      <ul>
        <li v-for="(item, index) in questionData.dataList[questionData.active].results" @click="viewQuestionDetail(index)" :class="['question-info-item', item.recent_answer ? 'has-footer' : '']">
          <div class="question-header">
            <img class="avatar" :src="item.asker.avatar" alt="" />
            <span class="name">{{ item.asker.nickname }}</span>
            <span class="price">￥{{ item.reward }}</span>
          </div>
          <div class="question-content">
            <div :class="[ 'question-desc', item.attachments.length ? 'dianping-type' : '']">
              <p class="question-text">{{ item.text }}</p>
              <div class="question-tags">
                <span v-if="item.purpose" class="tag-item tag-red">{{ item.purpose }}</span>
                <span v-if="item.catalog.name" class="tag-item">{{ item.catalog.name }}</span>
              </div>
            </div>
            <div v-if="item.attachments.length" class="question-painting">
              <img :src="item.attachments[0]" alt="">
            </div>
          </div>
          <div v-if="item.recent_answer" class="question-footer">
            <span class="master-name">{{ item.recent_answer.replier.nickname }}</span>
            <span v-if="item.recent_answer.replier.title" class="master-title">| {{ item.recent_answer.replier.title }}</span>
            <span class="dianping-time">{{ item.recent_answer.pastTimeStr }}点评</span>
          </div>
        </li>
      </ul>
    </div>
    <div class="master-wrapper">
      <div class="content-title-wrapper">
        <span class="title">名师推荐</span>
        <span @click="refreshMaster()" class="right-text">换一批</span>
      </div>
      <ul class="tags-tab">
        <li v-for="(item, index) in masterData.catalogs" @click="switchActive(1,index)" :class="['tag-item', masterData.active == index ? 'tag-selected' : '']">{{ item.name }}</li>
      </ul>
      <ul>
        <li v-for="(item, index) in masterData.dataList[masterData.active].results" @click="viewMasterDetail(index)" class="master-info-item">
          <div class="avatar-wrapper">
            <img class="avatar-image" alt="" :src="item.avatar" />
            <div class="level-wrapper">
              <p>{{ item.level.name[0] }}</p>
            </div>
          </div>
          <div class="info-wrapper">
            <div class="info-content">
              <p class="name">{{ item.realname }}</p>
              <span class="info">{{ item.title }}</span>
              <p class="info"> {{ item.answer_count }}回答 &nbsp;&nbsp; {{ item.fans_count }}粉丝</p>
            </div>
          </div>
          <div class="info-button-wrapper">
            <div @click="askMaster(index, $event)" class="action-btn btn-yellow">请教</div>
          </div>
        </li>
      </ul>
    </div>
    <div class="painting-wrapper">
      <div class="content-title-wrapper">
        <span class="title">精品画展</span>
        <span @click="refreshPainting" class="right-text">换一批</span>
      </div>
      <ul class="tags-tab">
        <li v-for="(item, index) in paintingData.catalogs" @click="switchActive(2,index)" :class="['tag-item', paintingData.active == index ? 'tag-selected' : '']">{{ item.name }}</li>
      </ul>
      <ul class="painting-images-wrapper">
        <li v-for="(item, index) in paintingData.dataList[paintingData.active].results" v-if="item.attachments.length" @click="viewPaintingDetail(index)" class="painting-item">
          <img class="painting-image" :src="item.attachments[0]" alt="" />
          <span class="painting-desc">{{ item.user.nickname }}</span>
        </li>
      </ul>
    </div>
    <search-popup :value="searchValue" :show-popup="showSearch" @close="closeSearch" ></search-popup>
    <footer-bar page="home"></footer-bar>
  </div>
</template>

<script>
import Vue from 'vue'
import qs from 'qs'

import * as consts from '@/util/const'
import request from '@/util/request'
import util from '@/util/util'

import Laziload from '@/components/vant/lazyload'

import FooterBar from '@/components/footerBar'
import Bubble from '@/components/bubble'
import SearchPopup from '@/components/searchPopup'

import Config from '@/config/config'

import { mapGetters } from 'vuex'
import Datetime from '@/util/datetime'

Vue.component(FooterBar.name, FooterBar)
Vue.component(Bubble.name, Bubble)
Vue.component(SearchPopup.name, SearchPopup)

Vue.use(Laziload)

export default {
  name: 'Home',
  data () {
    return {
      showSearch: false,
      searchValue: '',
      banners: [],
      masterData: {
        active: 0,
        catalogs: [{'name': '热门'}],
        dataList: [{results: []}]
      },
      paintingData: {
        active: 0,
        catalogs: [{'name': '热门'}],
        dataList: [{results: []}]
      },
      questionData: {
        active: 0,
        catalogs: [ {'name': '热门任务'}, {'name': '为你推荐' }],
        dataList: [{results: []}, {results: []}]
      },
      questionCatalogs: []
    }
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ])
  },
  beforeCreate () {
    var webUrl = window.location.href
    if (util.isIOS()) {
      this.SDKRegister(this, webUrl)
    }
  },
  created () {
    this.getBanners()
    this.getQuestionCatalogs()
    this.getMasterCatalogs()
    this.getPaintingCatalogs()
    this.getQuestionData(0)
    this.getMasterData(0)
    this.getPaintingData(0)
    this.setShare()
  },
  methods: {
    showSearchBar() {
      this.showSearch = true
    },
    closeSearch() {
      this.showSearch = false
    },
    getNews(id, callback) {
      var url = '/news/' + id + '/'
      var that = this
      // 调用登陆接口
      this.axios.get(url)
      .then(function (res) {
        if (res.status === 200) {
          that.news = res.data
          return callback(null, res.data)
        }
      })
      .catch(function (error) {
        return callback(error)
      })
    
    },
    viewBanner(index) {
      var banner = this.banners[index]
      console.log(banner)
      var params = { id: banner.object_id }
      switch(banner.type) {
        case 0:
          this.$router.push({ name: 'questionDetail', params: params })
          break;
        case 1:
          this.$router.push({ name: 'masterDetail', params: params })
          break;
        case 2:
          var that = this
          this.getNews(banner.object_id, function(err, news) {
            if (!err) {
              params.news = news
              that.$router.push({ name: 'newsDetail', params: params })
            }
          })
          break;
        case 3:
          this.$router.push({ name: 'paintingDetail', params: params })
          break;
        case 4:
          window.location.href = banner.url
          break;
        default:
          break;
      }
    }, 
    viewQuestionDetail(index) {
      var active = this.questionData.active
      var question = this.questionData.dataList[active].results[index]
      var params = { question: question, id: question.id }
      this.$router.push({ name: 'questionDetail', params: params })
    },
    viewMasterDetail(index) {
      var active = this.masterData.active
      var master = this.masterData.dataList[active].results[index]
      var params = { master: master, id: master.id }
      this.$router.push({ name: 'masterDetail', params: params })
    },
    viewPaintingDetail(index) {
      var active = this.paintingData.active
      var painting = this.paintingData.dataList[active].results[index]
      this.$router.push({ name: 'paintingDetail', params: { painting: painting }})
    },
    askMaster(index, event) {
      var active = this.masterData.active
      var master = this.masterData.dataList[active].results[index]
      this.$router.push({ name: 'questionRelease', params: { type: 2, master: master}})
      event.cancelBubble = true
    },
    getBanners() {
      var that = this
      // 调用登陆接口
      this.axios.get('/system/banner/')
      .then(function (res) {
        if (res.status === 200) {
          that.banners = res.data.results
        }
      })
    },
    getQuestionCatalogs: function() {
      var that = this
      if (this.$store.getters.questionCatalogs.length) {
        this.questionCatalogs = this.questionCatalogs.concat(this.$store.getters.masterCatalogs)
      } else {
        request.getCatalogs(consts.CATALOG_TYPE_QUESTION, function(err, res) {
          if (!err) {
            that.questionCatalogs = that.questionCatalogs.concat(res.results)
            var payload = {
              type: consts.CATALOG_TYPE_QUESTION,
              catalogs: res.results
            }
            that.$store.dispatch('getCatalogs', payload)
          }
        })
      }
    },
    getMasterCatalogs: function() {
      var that = this
      if (this.$store.getters.masterCatalogs.length) {
        this.masterData.catalogs = this.masterData.catalogs.concat(this.$store.getters.masterCatalogs)
        this.$store.getters.masterCatalogs.forEach(function() {
          that.masterData.dataList.push({results: []})
        })
      } else {
        request.getCatalogs(consts.CATALOG_TYPE_MASTER, function(err, res) {
          if (!err) {
            that.masterData.catalogs = that.masterData.catalogs.concat(res.results)
            res.results.forEach(function() {
              that.masterData.dataList.push({results: []})
            })
            var payload = {
              type: consts.CATALOG_TYPE_MASTER,
              catalogs: res.results
            }
            that.$store.dispatch('getCatalogs', payload)
          }
        })
      }
    },
    getPaintingCatalogs: function() {
      var that = this
      if (this.$store.getters.paintingCatalogs.length) {
        this.paintingData.catalogs = this.paintingData.catalogs.concat(this.$store.getters.paintingCatalogs)
        this.$store.getters.paintingCatalogs.forEach(function() {
          that.paintingData.dataList.push({results: []})
        })
      } else {
        request.getCatalogs(consts.CATALOG_TYPE_PAINTING, function(err, res) {
          if (!err) {
            that.paintingData.catalogs = that.paintingData.catalogs.concat(res.results)
            res.results.forEach(function() {
              that.paintingData.dataList.push({results: []})
            })
            var payload = {
              type: consts.CATALOG_TYPE_PAINTING,
              catalogs: res.results
            }
            that.$store.dispatch('getCatalogs', payload)
          }
        })
      }
    },
    switchActive(type, index) {
      if (type == 0) {
        this.questionData.active = index
        var data = this.questionData.dataList[index]
        if (!data.results.length) {
          this.getQuestionData(index)
        }
      } else if (type == 1) {
        this.masterData.active = index
        var data = this.masterData.dataList[index]
        if (!data.results.length) {
          this.getMasterData(index)
        }
      } else if (type == 2) {
        this.paintingData.active = index
        var data = this.paintingData.dataList[index]
        if (!data.results.length) {
          this.getPaintingData(index)
        }
      }
    },
    
    refreshMaster: function() {
      var data = this.masterData.dataList[this.masterData.active]
      if (data.next) {
        this.getMasterData(this.masterData.active, data.next)
      } else {
        this.$toast.fail('暂无更多内容')
      }
    },
    refreshPainting: function() {
      var data = this.paintingData.dataList[this.paintingData.active]
      if (data.next) {
        this.getPaintingData(this.paintingData.active, data.next)
      } else {
        this.$toast.fail('暂无更多内容')
      }
    },
    // 获取问答数据
    getQuestionData: function(index, next=null) {
      var params = {}
      var url = '/dianping/question/'
      if (!next) {
        if (!index) {
          params = { 'status': 2 }
        } else {
          var catalog = this.questionData.catalogs[index]
          params = { 'catalog': catalog.id }
        }
      } else {
        url = next
      }
      this.$toast.loading({ duration: 0 })
      var that = this
      // 调用登陆接口
      this.axios.get(url, { params: params })
      .then(function (res) {
        that.$toast.clear()
        if (res.status === 200) {
          for (var i=0; i< res.data.results.length; i++) {
            var item = res.data.results[i]
            if (item.recent_answer) {
              var datetime = new Datetime(item.recent_answer.created)
              item.recent_answer.pastTimeStr = datetime.getPastTime()
            }
          }
          that.questionData.dataList[index].results = res.data.results
          that.questionData.dataList[index].previous = res.data.previous
          that.questionData.dataList[index].next = res.data.next
          that.questionData.dataList[index].count = res.data.count
        }
      })
      .catch(function (error) {
        that.$toast.clear()
        console.log(error)
      })
    },
    
    getMasterData: function(index, next=null) {
      var params = {}
      var url = '/users/master/'
      if (!next) {
        if (!index) {
          params = { 'status': 2, 'user_type': 2 }
        } else {
          var catalog = this.masterData.catalogs[index]
          params = { 'catalog': catalog.id, 'user_type': 2 }
        }
      } else {
        url = next
      }
      this.$toast.loading({ duration: 0 })
      var that = this
      // 调用登陆接口
      this.axios.get(url, { params: params })
      .then(function (res) {
        that.$toast.clear()
        if (res.status === 200) {
          that.masterData.dataList[index].results = res.data.results
          that.masterData.dataList[index].previous = res.data.previous
          that.masterData.dataList[index].next = res.data.next
          that.masterData.dataList[index].count = res.data.count
        }
      })
      .catch(function (error) {
        that.$toast.clear()
        console.log(error)
      })
    },
    getPaintingData: function(index, next=null) {
      var params = {}
      var url = '/works/'
      if (!next) {
        if (!index) {
          params = { 'status': 2 }
        } else {
          var catalog = this.paintingData.catalogs[index]
          params = { 'catalog': catalog.id }
        }
      } else {
        url = next
      }
      this.$toast.loading({ duration: 0 })
      var that = this
      // 调用登陆接口
      this.axios.get(url, { params: params })
      .then(function (res) {
        that.$toast.clear()
        if (res.status === 200) {
          that.paintingData.dataList[index].results = res.data.results
          that.paintingData.dataList[index].previous = res.data.previous
          that.paintingData.dataList[index].next = res.data.next
          that.paintingData.dataList[index].count = res.data.count
        }
      })
      .catch(function (error) {
        that.$toast.clear()
        console.log(error)
      })
    },
    setShare: function() {
      var that = this
      var webUrl = window.location.href
      var route = webUrl.replace(Config.baseUrl, '')
      route = route.split('?')[0]
      this.wx.ready((res) => {
        // 分享到朋友圈
        var link = Config.baseUrl + '?route=' + route
        var title = '书画点评网'
        var imgUrl = 'http://p2buepmu3.bkt.clouddn.com/works/2018/03/12/cb18b3197e1f4a63874beba400706f6d.jpg'
        var desc = '做有质量的书画点评'
        that.wx.onMenuShareTimeline({
          title: title, // 分享标题
          link: link, // 分享链接
          imgUrl: imgUrl, // 分享图标
          success () {
            that.$toast.success('分享成功')
          },
          cancel () {
          }
        })
        // 分享给朋友
        that.wx.onMenuShareAppMessage({
          title: title, // 分享标题
          desc: desc, // 分享描述
          link: link, // 分享链接
          imgUrl: imgUrl, // 分享图标
          success: function () {
            that.$toast.success('分享成功')
          },
          cancel: function () {
          }
        })
      })
    
    }
  }
}

</script>

<style lang="scss" scoped>
@import '../../assets/style/main/home.scss'
</style>
